package com.IT.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//编写mybatis工具类
//sqlSessionFactory-->sqlSession
public class MybatisUtils {
    private static  SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //使用Mybatis获取sqlSessionFactory对象
            String resource = "mapper/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //既然有了SqlSessionFactory,顾名思义，我们可以从中获得SqlSession的实例
//Sqlsession结合了所有面向数据库执行sql命令的方法
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
}